package org.adorsys.aderp.jpa.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.util.ReflectionUtils;

/**
 * In order to manage automatic import, from non database world, 
 * we will be attaching the entity associated with this relationship whenever 
 * the enclosing entity is being saved.
 * 
 * For this to work, we have to be able to discover, the repository managing the related
 * entity and build the specification needed to read the related entity from it repository
 * given the business key.
 * 
 * This way if a data graph comes from the external world, we can use the business key to 
 * retrieve related entities and re-associate them.
 * 
 * @author francis
 *
 */
public class ToOneRelationshipInfo extends RepositoryResolver {

//	private final Field field;
	private final Method getterMethod;
	private final Method setterMethod;
	

	public ToOneRelationshipInfo(Field field, Method getterMethod, Method setterMethod,
			BeanFactory beanFactory) {
		super(beanFactory, field.getType());
//		this.field = field;
		this.getterMethod = getterMethod;
		this.setterMethod = setterMethod;
	}
	
	@SuppressWarnings("unchecked")
	public void attachField(Object target){
		Object entity = ReflectionUtils.invokeMethod(getterMethod, target);
		if(entity==null) return;
		Object attached = getRepository().findByBusinessKey(entity);
		if(attached==null) throw new IllegalArgumentException("Entity with business key " + entity + " not present in the database");
		if(entity!=attached)
			ReflectionUtils.invokeMethod(setterMethod, target, attached);
	}
	
}
